package com.yunhe.common.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author liuronglei
 */
public class StringUtil {
    public static boolean isEmpty(String str) {
        return str == null || "".equals(str);
    }

    public static boolean isNumber(String str) {
        for (int index = 0; index < str.length(); index++) {
            if (48 > (int) str.charAt(index) || (int) str.charAt(index) > 57) {
                return false;
            }
        }
        return true;
    }

    public static <T>T getValue(Optional<T> param) {
        return param.orElse(null);
    }

    /**
     * 根据指定表达式取得所有的匹配值
     * @param matchValue 查找的字符串
     * @param pattern 表达式
     * @return
     */
    public static List<String> getMatcherGroup(String matchValue, String pattern) {
        ArrayList<String> matcherGroup =  new ArrayList<>();
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(matchValue);
        while (m.find()) {
            matcherGroup.add(m.group(0));
        }
        return matcherGroup;
    }

    /**
     *查看字符串是否为电话，考虑到座机会有-
     * @param str 
     * @return boolean 
     * @create 2021/5/8 16:44
     */
    public static boolean isPhoneNumber(String str){
        for (int index = 0; index < str.length(); index++) {
            if ((48 > (int) str.charAt(index) || (int) str.charAt(index) > 57) &&  (int) str.charAt(index) != 45) {
                return false;
            }
        }
        return true;
    }

    public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }

    public static boolean containsIgnoreCase(String str, String searchStr) {
        if (str == null || searchStr == null) {
            return false;
        }
        int len = searchStr.length();
        int max = str.length() - len;
        for (int i = 0; i <= max; i++) {
            if (str.regionMatches(true, i, searchStr, 0, len)) {
                return true;
            }
        }
        return false;
    }

    public static boolean endsWith(String str, String suffix) {
        return endsWith(str, suffix, false);
    }

    private static boolean endsWith(String str, String suffix, boolean ignoreCase) {
        if (str == null || suffix == null) {
            return (str == null && suffix == null);
        }
        if (suffix.length() > str.length()) {
            return false;
        }
        int strOffset = str.length() - suffix.length();
        return str.regionMatches(ignoreCase, strOffset, suffix, 0, suffix.length());
    }


}
